<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-05
 * Time: 12:12
 */

namespace App\Http\Middleware;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Closure;
use Illuminate\Support\Facades\Auth;

class AdminLogin extends Controller
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param string|null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $excel = $request->excel;
        if($excel){
            $accessToken = $request->accessToken;
        }else{
            $accessToken = $request->header("accessToken");
        }
        if (!$accessToken) {
            return $this->apiResponse('', config('errorCode.PERMISSION_DENY'));
        }

        $admin = Admin::where("accessToken", $accessToken)->where('isDel', 0)->first();
        if (!$admin) {
            return $this->apiResponse('', config('errorCode.PERMISSION_DENY'));
        }
        if (!$admin['status']) {
            return $this->apiResponse('', config('errorCode.PERMISSION_DENY'));
        }
        $redisAccessToken = \RedisDB::get($admin['id'] . $admin['phone']);
        if(!$redisAccessToken || ($redisAccessToken != $accessToken)){
            return $this->apiResponse('', config('errorCode.PERMISSION_DENY'));
        }
        $request->ADMINID = $admin['id'];
        $request->ADMINPHONE = $admin['phone'];
        $request->ADMINUSERNAME = $admin['userName'];
        $request->RESOURCE = $admin['resource'];
        $request->pageSize = $request->pageSize ? $request->pageSize : 20;
        return $next($request);
    }
}
